package com.shell.customer.accreditation.rx;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.shell.customer.accreditation.AccreditEvent;
import com.shell.customer.accreditation.vo.AccreditationVo;
import com.shell.customer.base.service.CustomerService;
import com.shell.customer.group.service.CusGrpService;
import com.shell.customer.invitation.service.InvtCusService;
import com.shell.customer.po.CusGrp;
import com.shell.customer.po.CusInvt;
import com.shell.customer.po.CusRec;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;

@Component
public class SetGroupSubscriber extends OnErrorNotImplementedSubscriber<AccreditEvent> {
	@Autowired
	private CustomerService customerService;
	@Autowired
	private InvtCusService invtCusService;
	@Autowired
	private CusGrpService cusGrpService;

	public void onApplicationEvent(AccreditEvent event) {
		AccreditationVo accreditationVo = event.getAccreditationVo();
		CusRec cus = accreditationVo.getCustomerC();
		List<CusInvt> cusInvts = this.invtCusService.getCusInvtByCusName(cus.getCusName());
		if (cusInvts.size() > 0) {
			CusInvt cusInvt = (CusInvt) cusInvts.get(0);
			CusGrp cusGrp = (CusGrp) this.cusGrpService.selectByKey(cusInvt.getInviterId());
			if (cusGrp != null) {
				cus.setGrpId(cusGrp.getGrpId());
				cus.setGrpName(cusGrp.getGrpName());
			} else {
				CusRec inviter = (CusRec) this.customerService.selectByKey(cusInvt.getInviterId());
				cus.setGrpId(inviter.getGrpId());
				cus.setGrpName(inviter.getGrpName());
			}
		}
		this.customerService.updateNotNull(cus);
	}
}
